package common.io;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * Created by Gerardo on 1/25/14.
 */
public class Copier extends SimpleFileVisitor<Path> implements FileVisitor<Path> {
	private final Path srcRoot;
	private final Path dstRoot;

	@Inject
	public Copier(@Assisted("src") final Path srcRoot, @Assisted("dst") final Path dstRoot) {
		this.srcRoot = srcRoot;
		this.dstRoot = dstRoot;
	}

	@Override
	public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
		tryCopy(file, newDst(file));
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
		tryCopy(dir, newDst(dir));
		return FileVisitResult.CONTINUE;
	}

	private Path newDst(final Path path) {
		return dstRoot.resolve(srcRoot.relativize(path));
	}

	private void tryCopy(final Path source, final Path destination) throws IOException {
		try {
			Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
